//
//  ViewController.m
//  webViewPlayMedia
//
//  Created by iptv-macmini on 2021/3/31.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController () <WKNavigationDelegate,WKScriptMessageHandler>
@property(nonatomic, strong) WKWebView* webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化配置对象
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    // 默认是NO，这个值决定了用内嵌HTML5播放视频还是用本地的全屏控制
    configuration.allowsInlineMediaPlayback = YES;
    // 自动播放, 不需要用户采取任何手势开启播放
    // WKAudiovisualMediaTypeNone 音视频的播放不需要用户手势触发, 即为自动播放
    configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
    configuration.allowsAirPlayForMediaPlayback = YES;
    configuration.allowsPictureInPictureMediaPlayback = YES;
    NSString *jSString = @"document.getElementsByTagName('video')[0].setAttribute('playsinline','');";
    NSString *jSString2 = @"document.getElementsByTagName('video')[0].autoplay=true;";
    //用于进行JavaScript注入
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserScript *wkUScript2 = [[WKUserScript alloc] initWithSource:jSString2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [configuration.userContentController addUserScript:wkUScript];
    [configuration.userContentController addUserScript:wkUScript2];
    
    NSString *jSString3 = @"document.getElementsByTagName('video')[0].addEventListener('loadstart', function(e) {window.webkit.messageHandlers.readytoplay.postMessage(\"loadstart\");})";
    NSString *jSString4 = @"document.getElementsByTagName('video')[0].addEventListener('pause', function(e) {window.webkit.messageHandlers.pause.postMessage(\"pause\");})";
    NSString *jSString5 = @"document.getElementsByTagName('video')[0].addEventListener('play', function(e) {window.webkit.messageHandlers.play.postMessage(\"play\");})";
    NSString *jSString6 = @"document.getElementsByTagName('video')[0].addEventListener('ended', function(e) {window.webkit.messageHandlers.ended.postMessage(\"ended\");})";
    WKUserScript *wkUScript3 = [[WKUserScript alloc] initWithSource:jSString3 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [configuration.userContentController addUserScript:wkUScript3];
    WKUserScript *wkUScript4 = [[WKUserScript alloc] initWithSource:jSString4 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [configuration.userContentController addUserScript:wkUScript4];
    WKUserScript *wkUScript5 = [[WKUserScript alloc] initWithSource:jSString5 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [configuration.userContentController addUserScript:wkUScript5];
    WKUserScript *wkUScript6 = [[WKUserScript alloc] initWithSource:jSString6 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [configuration.userContentController addUserScript:wkUScript6];
    
    //添加一个协议
    [configuration.userContentController addScriptMessageHandler:self name:@"readytoplay"];
    [configuration.userContentController addScriptMessageHandler:self name:@"play"];
    [configuration.userContentController addScriptMessageHandler:self name:@"pause"];
    [configuration.userContentController addScriptMessageHandler:self name:@"ended"];
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    self.webView.navigationDelegate = self;
    NSURL *url =[NSURL URLWithString:@"https://www.zhangxinxu.com/study/201003/html5-video-mp4.html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    [self.view addSubview:self.webView];
    
    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                     withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                           error:&sessionError];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionRouteChange:)
                                                 name:AVAudioSessionRouteChangeNotification
                                               object:[AVAudioSession sharedInstance]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionMediaServicesWereLost:)
                                                 name:AVAudioSessionMediaServicesWereLostNotification
                                               object:[AVAudioSession sharedInstance]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionMediaServicesWereReset:)
                                                 name:AVAudioSessionMediaServicesWereResetNotification
                                               object:[AVAudioSession sharedInstance]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionSilenceSecondaryAudioHint:)
                                                 name:AVAudioSessionSilenceSecondaryAudioHintNotification
                                               object:[AVAudioSession sharedInstance]];
    
    
}

- (void)audioSessionRouteChange:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    NSLog(@"audioSessionRouteChange  %@",userInfo);
    AVAudioSessionRouteDescription *routeDescription = userInfo[@"AVAudioSessionRouteChangePreviousRouteKey"];
    AVAudioSessionPortDescription *portDescription = routeDescription.outputs[0];
    NSLog(@"audioSession=portDescription  %@",portDescription.portType);
}

- (void)audioSessionMediaServicesWereLost:(NSNotification *)notification
{
    NSLog(@"audioSessionServicesWereLost");
}

- (void)audioSessionMediaServicesWereReset:(NSNotification *)notification
{
    NSLog(@"audioSessionMediaServicesWereReset");
}

- (void)audioSessionSilenceSecondaryAudioHint:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    NSLog(@"audioSessionSilenceSecondaryAudioHint  %@",userInfo);
}

# pragma mark WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"WSPhoneWebView decidePolicyForNavigationAction %@",navigationAction.request.URL);
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"WSPhoneWebView didStartProvisionalNavigation");
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"WSPhoneWebView didFailProvisionalNavigation");
    
    if (error.code == NSURLErrorTimedOut ||
        error.code == NSURLErrorNotConnectedToInternet ||
        error.code == NSURLErrorCannotConnectToHost) {
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"WSPhoneWebView didFinishNavigation");
    
    NSString *JsStr = @"(document.getElementsByTagName(\"video\")[0]).src";
    [self.webView evaluateJavaScript:JsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        if(![response isEqual:[NSNull null]] && response != nil){
            //截获到视频地址了
            NSLog(@"response == %@",response);
        }else{
            //没有视频链接
        }
    }];
    
    NSString *JsStr2 = @"(document.getElementsByTagName(\"video\")[0]).duration";
    [self.webView evaluateJavaScript:JsStr2 completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        if(![response isEqual:[NSNull null]] && response != nil){
            //截获到视频地址了
            NSLog(@"duration == %@",response);
        }else{
            //没有视频链接
        }
    }];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"WSPhoneWebView didFailNavigation");
    if (error.code == NSURLErrorTimedOut ||
        error.code == NSURLErrorNotConnectedToInternet) {
        
    }
}

#pragma mark - WKScriptMessageHandler

//! WKWebView收到ScriptMessage时回调此方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name caseInsensitiveCompare:@"readytoplay"] == NSOrderedSame) {
        NSLog(@"video is readytoplay");
    }
    if ([message.name caseInsensitiveCompare:@"play"] == NSOrderedSame) {
        NSLog(@"video is play");
    }
    if ([message.name caseInsensitiveCompare:@"pause"] == NSOrderedSame) {
        NSLog(@"video is pause");
    }
    if ([message.name caseInsensitiveCompare:@"ended"] == NSOrderedSame) {
        NSLog(@"video is ended");
    }
}

@end
